package com.alipay.zxy.alipayplugin.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.zxy.alipayplugin.config.AlipayConfig;
import com.alipay.zxy.alipayplugin.config.DefaultAlipayClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zxy
 */
@Slf4j
@Service
public class AlipaySystemOauthTokenService extends BaseService {
    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipaySystemOauthTokenService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public AlipaySystemOauthTokenResponse query(String authCode) throws AlipayApiException {
        //初始化请求类
        AlipaySystemOauthTokenRequest alipayRequest = new AlipaySystemOauthTokenRequest();
        alipayRequest.setCode(authCode);
        alipayRequest.setGrantType("authorization_code");
        alipayRequest = (AlipaySystemOauthTokenRequest) getAlipayRequest(alipayRequest, alipayConfig, null);
        AlipayClient alipayClient = DefaultAlipayClientFactory.getInstance(alipayConfig);
        log.info("支付宝请求参数alipayRequest：{}", JSONObject.toJSONString(alipayRequest));
        AlipaySystemOauthTokenResponse alipayResponse = alipayClient.execute(alipayRequest);
        if (alipayResponse.isSuccess()) {
            log.info("alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            return alipayResponse;
        } else {
            log.info("支付宝用户token刷新错误 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            return null;
        }
    }
}
